const staticData = require('../../utils/util.js')

Page({
  data: {
    timeDiff: {
      days: 0,
      hours: 0,
      minutes: 0,
      seconds: 0
    },
    ...staticData
  },

  onLoad: function(options) {
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('updateData', (data) => {
      console.log('接收到更新数据:', data);
      this.setData({
        FirstData: data.FirstData,
        ChatData: data.ChatData,
        MostChat: data.MostChat,
        DeepChat: data.DeepChat,
        CardData: data.CardData
      });
      this.calculateTimeDiff(); // 重新计算时间差
    });

    this.startTimer();
  },

  onUnload: function() {
    this.stopTimer();
  },

  startTimer: function() {
    this.calculateTimeDiff();
    this.timer = setInterval(() => {
      this.calculateTimeDiff();
    }, 1000);
  },
  stopTimer: function() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },
  calculateTimeDiff: function() {
    const firstData = this.data.FirstData;
    // 构造目标日期对象
    // 使用iOS兼容的日期格式 yyyy/MM/dd HH:mm:ss
    const targetDate = new Date(
      `${firstData.firstYear}/${firstData.firstMonth}/${firstData.firstDay} ${firstData.firstHour}:${firstData.firstMinute}:${firstData.firstSecond}`
    );
    const now = new Date();
    
    // 计算时间差（毫秒）
    const diff = now - targetDate;
    
    // 计算天数、小时、分钟、秒
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((diff % (1000 * 60)) / 1000);

    this.setData({
      timeDiff: { days, hours, minutes, seconds }
    });
  }
});